package com.example.controller;

import com.example.PcUtils.UploadFileUtils;
import com.example.TokenUtil.GetCookie;
import com.example.userdome.pojo.Images;
import com.example.userdome.pojo.LoginRequest;
import com.example.userdome.pojo.Result;
import com.example.userdome.service.UserService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    private UserService userService;

    //登录接口
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest,HttpServletResponse response, HttpServletRequest request) {
        return userService.userLogin(loginRequest, response,request);
    }
    //上传图片接口
    @PostMapping("/saveImage")
    public Result<T> saveImage(Images images,
                               HttpServletResponse response,
                               HttpServletRequest request)throws ServletException, IOException {
        String cookieValue = request.getHeader("Cookie");
        String token = GetCookie.getCookieValue(cookieValue);
        Part HeaderfilePart = request.getPart("avatar"); // 获取上传文件
        if (HeaderfilePart != null) {
            UploadFileUtils.FileResult result = UploadFileUtils.savePart(request, HeaderfilePart);
            images.setPath(result.getUrl());
        }
        //新增用户信息
        return userService.saveImage(images,token,response,request);
    }
}
